import store from "./store";
import { getPermMenuApi } from "api/api";
import { getWorkOrderCountByStatusApi } from "api/taskCenterApi";

function getAsideMenu(pid, data) {
  let arr = [];
  data.forEach((item) => {
    if (pid === item.pid) {
      item["children"] = getAsideMenu(item.id, data);
      arr.push(item);
    }
  });
  return arr;
}
function getPathname() {
  let pathname = window.location.pathname;
  let paths = pathname.split("/");
  let type = "",
    source = "";
  if (paths.length >= 2) {
    type = paths[2];
    source = paths[3];
  }

  return { type, source };
}
function setMenu() {
  getPermMenuApi().then(async (res) => {
    console.log("getPermMenuApi", res);
    let data = res.data;
    let firstLevelMenu = data.filter((item) => item.pid == 0);
    console.log("firstLevelMenu", firstLevelMenu);
    let menu = {};
    console.log("[ getPathname() ] >", getPathname());
    firstLevelMenu.forEach((item) => {
      menu[item.url] = getAsideMenu(item.id, data);
    });
    if (getPathname().type === "task") {
      let asideMenu = menu["/task"];
      let { data } = await getWorkOrderCountByStatusApi();

      for (let i = 0; i < asideMenu.length; i++) {
        let status = asideMenu[i].url.split("/")[2];
        // asideMenu[i].name = `${asideMenu[i].name} ( ${data[status]} )`;
        asideMenu[i].name = `${asideMenu[i].name}`;
      }
    }
    store.commit("setMenu", { firstLevelMenu, asideMenu: menu });
    console.log("menu", menu);
  });
}
export default setMenu;
